import { useDeepCompareEffect } from 'ahooks';
import { Modal, Radio, Space } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import styles from './index.less';
import MonthPicker from './MonthPicker';
import WeekPicker from './WeekPicker';

type TProps = {
  visible: boolean;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
  data: any;
};

const PeriodPickerModal: FC<TProps> = (props) => {
  const { visible, onSubmit, onCancel, data } = props;
  const [weekChecked, setWeekChecked] = useState<number[]>([]);
  const [monthChecked, setMonthChecked] = useState<number[]>([]);
  const [curType, setCurType] = useState<string>('week');

  const handleWeekChange = (val: number[]) => {
    setWeekChecked(val);
  };
  const handleMonthChange = (val: number[]) => {
    setMonthChecked(val);
  };

  const handleTypeChange = (e: any) => {
    setCurType(e.target.value);
  };

  const handleSubmit = () => {
    onSubmit &&
      onSubmit({
        type: curType,
        value: curType === 'week' ? weekChecked : monthChecked,
      });
  };

  useDeepCompareEffect(() => {
    const { type, value } = data;
    setCurType(type);
    if (type === 'week') {
      setWeekChecked(value || []);
    } else {
      setMonthChecked(value || []);
    }
  }, [data]);

  return (
    <Modal title="选择时间" open={visible} width={600} onCancel={onCancel} onOk={handleSubmit}>
      <div className="mb-16">
        <Radio.Group value={curType} onChange={handleTypeChange}>
          <Space size={16}>
            <Radio value="week">按周</Radio>
            <Radio value="month">按月</Radio>
          </Space>
        </Radio.Group>
      </div>
      <div className={styles.choseWrap}>
        {curType === 'week' ? (
          <WeekPicker value={weekChecked} onChange={handleWeekChange} />
        ) : (
          <MonthPicker value={monthChecked} onChange={handleMonthChange} />
        )}
      </div>
    </Modal>
  );
};

export default PeriodPickerModal;
